import request from '@/utils/request'

// User Information interface
export interface UserInfo {
  userId: number
  username: string
  realName?: string
  phone?: string
  email?: string
  role?: string
  status?: number
  createdAt?: string
  updatedAt?: string
}

// Request parameters for user list
interface UserListParams {
  page?: number;
  pageSize?: number;
  username?: string;
  status?: boolean;
}

// Response structure for user list
interface UserListResponse {
  code: number;
  message: string;
  data: {
    list: UserInfo[];
    total: number;
    page: number;
    pageSize: number;
  } | null;
}

// Request parameters for user login
interface LoginParams {
  username?: string
  password?: string
}

// Response data for user login
interface LoginResponseData {
  token?: string
  user?: UserInfo
}

// Response for user login
interface LoginResponse {
  code: number
  message: string
  data: LoginResponseData | null
}

// API function for user login
function login(data: LoginParams) {
  return request.post<LoginResponse>('/auth/login', data)
}

// Request parameters for user registration
interface RegisterParams {
  username?: string
  password?: string
  realName?: string
  phone?: string
  email?: string
}

// Response for user registration
interface RegisterResponse {
  code: number
  message: string
  data?: any // Adjust based on actual API response
}

// API function for user registration
function register(data: RegisterParams) {
  return request.post<RegisterResponse>('/register', data)
}

// Request parameters for updating user password
export interface UpdatePasswordData {
  oldPassword?: string
  newPassword?: string
}

// API function for updating user password (backend gets user ID from token)
function updatePassword(data: UpdatePasswordData) {
  return request.post('/updateUserPwd', data)
}

// Request params for updating user info
export interface UpdateUserInfoParams {
  realName?: string
  phone?: string
  email?: string
}

// Response structure for updating user info (can reuse UserInfo if the response data matches)
export type UpdateUserInfoResponse = UserInfo // Assuming the data field in the response is the updated UserInfo object

// API function to update user info
function updateUserInfo(data: UpdateUserInfoParams) {
  return request.put<UpdateUserInfoResponse>('/updateUserInfo', data);
}

// API function for getting user list
function getUserList(params: UserListParams) {
  return request.get<UserListResponse>('/users', { params });
}

// API function for deleting a user by ID (backend requires admin role)
function deleteUser(id: number) {
    return request.delete('/deleteUser', { params: { id } });
}

const userApi = {
  login,
  register,
  updatePassword,
  updateUserInfo,
  getUserList,
  deleteUser, // Add the new deleteUser function
}

export default userApi